package runnable;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

import data.TimerJob;

import utils.Msg;
import utils.SSHUtils;
import utils.Utils;

import jsonobj.JobInfo;
import jsonobj.Message;

public class JobMonitor implements Runnable, Msg {
	JobInfo ji;
	TimerJob tj;
	
	public JobMonitor(JobInfo j,TimerJob t) {
		this.ji = j;
		this.tj = t;
	}

	public void run() {
		boolean queued = false;
		boolean running = false;
		Process child;
		try {

			Runtime run = Runtime.getRuntime();
			
			while (true) {
				String s;
				String cmdd = "qstat | grep " + System.getProperty("user.name")
				+ " | grep " + ji.jname
				+ " | awk '{print($5)}'" ;
				if ((s = Utils.runCmd(cmdd)) != null) {
					//Utils.out("OUT WAS "+s);
					switch (s.charAt(0)) {
					
					case 'Q':
						if(!queued)
						{
							Utils.ws.send(new Message(JOB_QUEUED, ji.jname));
							queued = true;
						}
						break;
					case 'R':
						if(!running)
						{
							Utils.ws.send(new Message(JOB_EXECUTING, ji.jname));
							tj.endQueued();
							running = true;
						}
						break;
					}
				} else
					break;
				
				// TODO sleep according to walltime
				if(running)
					Thread.sleep(10000);
				else
					Thread.sleep(2000);
			}
			Utils.out("+ job terminated: "+ji.jname);
			/*if (!ji.isSire) {
				String outfile = ji.jobname + "/" + ji.jobname + ".out";
				if (!SSHUtils.ScpTo(new File(outfile).getPath(), "~/" + outfile)) {
					Utils.out("FAILED RETREIVNG FILE " + ji.filename);
					Utils.ws.send(new Message(JOB_FAILED, ji.jobname));
					return;
				}
			}*/
			///if (ji.isSire) {
				Utils.out("+ zipping file "+ji.jname);
				String outfile = ji.jname+"_results.zip";
				child = run.exec(
						"zip -r " + outfile+" ./" + ji.jname);
				if (child.waitFor() != 0)
					return;
				Utils.out("+ sftp: uploading file"+outfile);
				if (!SSHUtils.ScpTo(new File(outfile).getPath(), "~/"
						+ ji.jname + "/" + outfile)) {
					Utils.out("FAILED RETREIVNG FILE sire "
							+ ji.jname);
					Utils.ws.send(new Message(JOB_FAILED, ji.jname));
					return;
				}
				Utils.out("+ cleaning up...");
				child = run.exec("rm " + outfile);
				if (child.waitFor() != 0)
				{
					Utils.out("ERROR REMOVING ZIP "+outfile);
				}
				child = run.exec("rm -r " + ji.jname);
				if (child.waitFor() != 0)
				{
					Utils.out("ERROR REMOVING DIR "+ji.jname);
				}
			//}
				Utils.out("+ terminating job monitor thread");
				Utils.ws.send(new Message(JOB_TERMINATED, ji.jname));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
